package armserver.server;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;

import org.apache.log4j.Logger;

import arm.AppResourceManager;
import arm.impl.StdAppResourceManager;

public class ArmServer implements ArmServerMBean {

	private static final Logger log = Logger.getLogger(ArmServer.class);
	private AppResourceManager arm;
	private ArmServerControllerMBean armController;
	private MBeanServer server;
    private static final String objectName = ArmServerConstant.DEFAUTL_DOMAIN+":service=ArmServerInstance";
	private enum STATE {
		INIT, CONFIG, START, RUNNING, STOP
	};
	private STATE state;

	public void init()
	{
		
	}
	
	public void start() throws ArmException {

		arm = new StdAppResourceManager();
		state = STATE.INIT;
		try {
			arm.start();
			state = STATE.CONFIG;
		} catch (Exception e) {
			e.printStackTrace();
		}
		server = arm.getMBeanServer();
		state = STATE.START;
		try {
			server.registerMBean(this, new ObjectName(this.objectName));
		} catch (InstanceAlreadyExistsException e) {
			e.printStackTrace();
		} catch (MBeanRegistrationException e) {
			e.printStackTrace();
		} catch (NotCompliantMBeanException e) {
			e.printStackTrace();
		} catch (MalformedObjectNameException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
		}

		armController = ArmServerController.getInstance();
		armController.setMBeanServer(server);
		try {
			armController.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
		armController.install();
		state = STATE.RUNNING;
	}

	public void shutdown() throws ArmException {

		try {
			armController.stop();
			arm.stop();
			server.unregisterMBean(new ObjectName(this.objectName));
			state = STATE.STOP;
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public String getState() throws ArmException {
		
		return state.name();
	}

}
